<template>
  <div class="app-container">
    <div v-show="!modifyInfo.visible && !detailInfo.visible">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          ref="pageFilter"
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </new-page-filter>
      </div>

      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btList">
          <template v-slot:filter-submit>
            <el-button :disabled="!canSubmit" @click="submit">提交</el-button>
          </template>
          <template v-slot:filter-check>
            <el-button :disabled="!canCheck" @click="check">审核</el-button>
          </template>
          <template v-slot:filter-revoke>
            <el-button :disabled="!canRevoke" @click="revoke">撤回</el-button>
          </template>
          <template v-slot:filter-reject>
            <el-button :disabled="!canReject" @click="reject">驳回</el-button>
          </template>
          <template v-slot:filter-print>
            <el-button @click="print">打印</el-button>
          </template>
          <template v-slot:filter-excel>
            <el-button @click="exportExcel">导出excel</el-button>
          </template>
          <template v-slot:filter-import>
            <el-upload
              :headers="uploadInfo.headers"
              :show-file-list="false"
              :on-error="uploadError"
              :on-success="importAssetApplication"
              :before-upload="beforeProductUpload"
              :action="uploadInfo.action"
            >
              <el-button>导入</el-button>
            </el-upload>
          </template>
        </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :tab-index="false"
        :check-box="true"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @pageInfo="pageInfo"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <p class="slip-edit" @click="showDetail(scope.row)">
            {{ scope.row.orderNo || '-' }}
          </p>
        </template>
      </table-container>
    </div>
    <!-- 新增或修改 -->
    <assetApplicationModify
      v-if="modifyInfo.visible"
      :id="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />

    <!-- 详情页 -->
    <assetApplication-detail
      v-if="detailInfo.visible"
      :id="detailInfo.id"
      v-model:visible="detailInfo.visible"
      :title="detailInfo.title"
      @returnBack="getList"
    />

    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      :field-list="tableInfo.fieldList"
      v-model:form-data="advancedSearchInfo.data"
      @callback="advancedSearchCallback"
    />

    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio label="page">当前页数据</el-radio>
          <el-radio label="all">全部页数据</el-radio>
          <el-radio label="select">仅选择数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="assetApplication">
import {
  getAssetApplicationCustomizeListPage,
  getAssetApplicationCustomizeListAll,
  assetApplicationSubmit,
  assetApplicationCheck,
  assetApplicationDelete,
  assetApplicationRevoke,
  assetApplicationReject,
  printAssetApplicationList,
  exportAssetApplicationList,
} from '@/api/asset.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { fatchTemplateByCode } from '@/api/base'
import { ElLoading } from 'element-plus'
import assetApplicationModify from './modify.vue'
import assetApplicationDetail from './details.vue'
import { exportTemplateExcel } from '@/api/pub'
import axios from 'axios'

const { proxy } = getCurrentInstance()
const route = useRoute()
const props = defineProps(['query'])
const uploadInfo = ref({
  action: axios.defaults.baseURL + '/asset/application/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})

const listTypeInfo = ref({
  typeList: [],
})
const filterInfo = ref({
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      id: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '',
      },
    },
    queryParams: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('assetApplication:add'),
    },
    {
      type: 'slot',
      value: 'submit',
      show: proxy.$permission('assetApplication:submit'),
    },
    {
      type: 'slot',
      value: 'check',
      show: proxy.$permission('assetApplication:check'),
    },
    {
      type: 'slot',
      value: 'revoke',
      show: proxy.$permission('assetApplication:revoke'),
    },
    {
      type: 'slot',
      value: 'reject',
      show: proxy.$permission('assetApplication:reject'),
    },
    {
      type: 'slot',
      value: 'excel',
      show: proxy.$permission('assetApplication:excelList'),
    },
    {
      type: 'slot',
      value: 'print',
      show: proxy.$permission('assetApplication:printList'),
    },
    {
      type: 'button',
      label: '下载模板',
      event: downloadTemplate,
      show: proxy.$permission('assetApplication:downloadTemplate'),
    },
    {
      type: 'slot',
      value: 'import',
      show: proxy.$permission('assetApplication:import'),
    },
  ],
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('assetApplication:delete'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '修改',
        event: update,
        show: proxy.$permission('assetApplication:update'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('assetApplication:submit'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '审核',
        event: check,
        show: proxy.$permission('assetApplication:check'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '撤回',
        event: revoke,
        show: proxy.$permission('assetApplication:revoke'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '驳回',
        event: reject,
        show: proxy.$permission('assetApplication:reject'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
    ],
  },
})
const printerInfo = ref({
  visible: false,
  data: {},
})
const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
const detailListInfo = ref({
  visible: false,
})
//明细相关
const detailInfo = ref({
  visible: false,
  title: '报修单详情',
  id: '',
})
//新增或更新相关
const modifyInfo = ref({
  visible: false,
  title: '',
  id: '',
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const page = ref({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})

const canSubmit = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter((item) => item.status !== 1).length
  )
})
const canCheck = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter((item) => item.status !== 2).length
  )
})
const canReject = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter((item) => item.status !== 2).length
  )
})
const canRevoke = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter((item) => item.status !== 2).length
  )
})

// watch(
//   () => route,
//   () => {
//     getList()
//   },
//   {
//     deep: true,
//     immediate: true,
//   }
// )
// watch(
//   () => estimateInfo.value.formInfo.data,
//   (val) => {
//     if (val) {
//       if (
//         (val.isRepair == 1 || val.isRepair == 0) &&
//         val.compositeScore &&
//         val.serviceAttitude &&
//         val.responseSpeed &&
//         val.skillLevel
//       ) {
//         estimateInfo.value.btList[1].disabled = false
//       } else {
//         estimateInfo.value.btList[1].disabled = true
//       }
//     } else {
//       estimateInfo.value.btList[1].disabled = true
//     }
//   },
//   {
//     deep: true,
//   }
// )

setData()
function setData() {
  let obj = {
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'asset_application_status',
      show: false,
      hidden: true,
    },
    assetName: {
      label: '资产名称',
      value: 'assetName',
      type: 'column',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
function downloadTemplate() {
  exportTemplateExcel('asset_application_import').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}

function handleClose() {
  dialogInfo.value.visible = false
}
//删除附件
function uploadRemove(file, fileList) {
  registerInfo.value.formInfo.data.fileUrlList = []
  if (fileList.length) {
    fileList.forEach((item) => {
      registerInfo.value.formInfo.data.fileUrlList.push(item.response.data[0])
    })
  } else {
    registerInfo.value.formInfo.data.fileUrlList = []
  }
}
async function print() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'print'
  dialogInfo.value.msg = '请选择当数据打印范围'
  dialogInfo.value.btList[1].label = '打印'
  dialogInfo.value.flag = 'page'
}
function exportExcel() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'excel'
  dialogInfo.value.msg = '请选择数据导出范围'
  dialogInfo.value.btList[1].label = '导出'
  dialogInfo.value.flag = 'page'
}
function checkConfirm() {
  if (dialogInfo.value.type === 'excel') {
    exportExcelList()
  } else if (dialogInfo.value.type === 'print') {
    printList()
  }
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
function exportExcelList() {
  if (dialogInfo.value.flag === 'select') {
    if (!tableInfo.value.selections.length) {
      proxy.$message.warning({
        message: '请选择数据！',
        showClose: true,
        duration: 3000,
      })
      return
    }
    let ids = tableInfo.value.selections.map((item) => item.id).join(',')
    filterInfo.value.query.queryMap.id.value = ids
  }else{
    filterInfo.value.query.queryMap.id.value = ''
  }
  let params = {
    ...filterInfo.value.query,
    ...page.value,
    page: dialogInfo.value.flag === 'page' ? true : false,
  }
  exportAssetApplicationList(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function printList() {
  fatchTemplateByCode({
    resourceCode: 'assetApplication:printList',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogInfo.value.flag)
    }
  })
}
function getPrintData(temp, flag) {
  if (dialogInfo.value.flag === 'select') {
    if (!tableInfo.value.selections.length) {
      proxy.$message.warning({
        message: '请选择数据！',
        showClose: true,
        duration: 3000,
      })
      return
    }
    let ids = tableInfo.value.selections.map((item) => item.id).join(',')
    filterInfo.value.query.queryMap.id.value = ids
  }
  else{
    filterInfo.value.query.queryMap.id.value = ''
  }
  let query = {
    customizeDto: filterInfo.value.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: dialogInfo.value.flag === 'page' ? true : false,
  }
  printAssetApplicationList(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
// 编辑
function update(data) {
  sessionStorage.setItem('storeRowId', data.id)
  modifyInfo.value.visible = true
  modifyInfo.value.title = '修改资产申购论证'
  // 显示信息
  modifyInfo.value.id = data.id
}
//提交
function submit(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  assetApplicationSubmit(ids).then((resp) => {
    if (resp.success) {
      tableInfo.value.refresh = Math.random()
    }
  })
}
//审核
function check(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  assetApplicationCheck(ids).then((resp) => {
    if (resp.success) {
      tableInfo.value.refresh = Math.random()
    }
  })
}
//删除
function remove(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  assetApplicationDelete(ids).then((resp) => {
    if (resp.success) {
      tableInfo.value.refresh = Math.random()
    }
  })
}
//撤回
function revoke(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  assetApplicationRevoke(ids).then((resp) => {
    if (resp.success) {
      tableInfo.value.refresh = Math.random()
    }
  })
}
//驳回
function reject(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  assetApplicationReject(ids).then((resp) => {
    if (resp.success) {
      tableInfo.value.refresh = Math.random()
    }
  })
}
function handleExceed(files, fileList) {
  proxy.$message.warning(
    ` 只能上传 ${registerInfo.value.uploadInfo.limit} 个文件`
  )
}
function beforeProductUpload(file) {
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })

  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}
//上传附件
function uploadAttachment(resp, file) {
  registerInfo.value.uploadInfo.loading.close()
  if (resp && resp.success) {
    registerInfo.value.formInfo.data.fileUrlList.push(resp.data[0])
  }
}
function uploadError(err) {
  if (err) {
    proxy.$message.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
function importAssetApplication(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    proxy.$message.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    proxy.$message.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}

function pageInfo(obj) {
  page.value = obj
}
// function handleCloseEstimate() {
//   estimateInfo.value.visible = false
// }
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.visible = true
  detailInfo.value.title = '资产申购论证详情'
  detailInfo.value.id = row.id
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function returnModify() {
  if (modifyInfo.value.id) {
    getList()
  } else {
    search()
  }
}
// 创建
function create() {
  modifyInfo.value.visible = true
  modifyInfo.value.title = '新增资产申购论证'
  modifyInfo.value.id = null
}
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  let arr = [
    {
      asTbName: 'repair_order',
      columnName: 'repair_dept_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'deptAuth',
    },
  ]
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
async function getList() {
  tableInfo.value.refresh = Math.random()
}
function search() {
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'assetApplicationList-com.slip.spd.entity.vo.device.DeviceApplicationVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )

      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getAssetApplicationCustomizeListPage
      getList()
    }
  })
}
</script>

<style scoped></style>
